#include "raySDL.h"

SDL_Window* g_Window = NULL;
SDL_Renderer* g_Renderer = NULL;

bool Init(const string title_name, const int screen_width, const int screen_heignt, IMG_InitFlags img_InitFlag)
{
	// 初始化SDL
	if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
	{
		cout << "SDL could not initialize! SDL Error: " << SDL_GetError() << endl;
		return false;
	}

	// 设置纹理为线性过滤
	if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
	{
		cout << "Warning: Linear texture filtering not enabled!";
	}

	// 创建窗口
	g_Window = SDL_CreateWindow(title_name.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screen_width, screen_heignt, SDL_WINDOW_SHOWN);
	if (g_Window == NULL)
	{
		cout << "Window could not be created! SDL Error: " << SDL_GetError() << endl;
		return false;
	}

	// 为窗口创建垂直同步渲染器
	g_Renderer = SDL_CreateRenderer(g_Window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (g_Renderer == NULL)
	{
		cout << "Renderer could not be created!SDL Error : " << SDL_GetError() << endl;
		return false;
	}

	// 初始化渲染颜色
	SDL_SetRenderDrawColor(g_Renderer, 0xFF, 0xFF, 0xFF, 0xFF);

	// 初始化PNG加载
	int imgFlags = img_InitFlag;
	if (!(IMG_Init(imgFlags) & imgFlags))
	{
		cout << "SDL_image could not initialize! SDL_image Error: " << IMG_GetError() << endl;
		return false;
	}

	// 初始化SDL_ttf
	if (TTF_Init() == -1)
	{
		cout << "SDL_ttf could not initialize! SDL_ttf Error:%s" << TTF_GetError() << endl;
		return false;
	}

	// 初始化SDL_mixer
	if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
	{
		cout << "SDL_mixer could not initialize! SDL_mixer Error: " << Mix_GetError() << endl;
		return false;
	}

	return true;
}

void Close()
{
	// 销毁渲染器
	if (g_Renderer != NULL)
	{
		SDL_DestroyRenderer(g_Renderer);
		g_Renderer = NULL;
	}

	// 销毁窗口
	if (g_Window != NULL)
	{
		SDL_DestroyWindow(g_Window);
		g_Window = NULL;
	}

	// 退出Mix
	Mix_Quit();

	// 退出TTF
	TTF_Quit();

	// 退出IMG
	IMG_Quit();

	// 退出SDL
	SDL_Quit();
}